<template>
  <a-modal :width="1000" v-model:visible="showAddDialog" :title="`分时策略-${PolicyType[formInfo.policyType]}`" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <div class="edit-con">
      <div class="title">基础信息</div>
      <a-form ref="formRef" :model="formInfo" :rules="rules">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="policyName" label="策略名称:" label-col-flex="100px">
              <a-input v-model="formInfo.policyName" placeholder="请输入" allow-clear :max-length="40" show-word-limit />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="生效日期：" label-col-flex="100px">
              <a-date-picker v-model="formInfo.effectiveStartDate" placeholder="开始日期(必填)" />
              <span style="margin: 0 5px">-</span>
              <a-date-picker v-model="formInfo.effectiveEndDate" placeholder="结束日期" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="isShare" label="是否共享：" label-col-flex="100px">
              <a-radio-group v-model="formInfo.isShare">
                <a-radio :value="1">共享</a-radio>
                <a-radio :value="0">不共享</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="marketplaceIds" label="适用站点：" label-col-flex="100px">
              <a-select v-model="formInfo.marketplaceIds" multiple :max-tag-count="2" placeholder="请选择" value-key="id" allow-search allow-clear>
                <a-option v-for="(markedt, i) in markedtList" :key="i" :value="markedt.value" :label="markedt.label" />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="title">策略配置</div>
      <BudgetTemplate v-if="policyType === 'BUDGET_POLICY'" :currentData="currentData" :ref="refsMap.budgetRef" />
      <BidTemplate v-if="policyType === 'BIDDING_POLICY'" :currentData="currentData" :ref="refsMap.bidRef" />
      <SwitchTemplate v-if="policyType === 'SWITCH_POLICY'" :currentData="currentData" :ref="refsMap.switchRef" />
      <TargetingTemplate v-if="policyType === 'TARGETING_POLICY'" :currentData="currentData" :ref="refsMap.targetingRef" />
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import { PolicyType } from '../../types'
  import BudgetTemplate from './budgetTemplate.vue'
  import BidTemplate from './bidTemplate.vue'
  import SwitchTemplate from './switchTemplate.vue'
  import TargetingTemplate from './targetingTemplate.vue'
  import { createPolicyTemplateList } from '@/api/advert'
  import { Message } from '@arco-design/web-vue'
  onMounted(() => {
    if (props.currentData?.id) {
      formInfo.value = {
        isShare: props.currentData?.isShare,
        policyName: props.currentData?.policyName,
        effectiveStartDate: props.currentData?.effectiveStartDate,
        effectiveEndDate: props.currentData?.effectiveEndDate,
        marketplaceIds: props.currentData?.applicableMarketplace?.split(','),
        policyType: props.policyType,
        policyId: props.currentData?.id,
      }
    } else {
      formInfo.value = {
        isShare: 0,
        policyType: props.policyType,
      }
    }
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    markedtList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    policyType: {
      type: String,
      default: 'BUDGET_POLICY',
    },
    currentData: {
      type: Object,
      default: () => {},
    },
  })

  const rules = ref({
    policyName: [{ required: true, message: '请输入策略名称' }],
    isShare: [{ required: true, message: '请选择是否共享' }],
    marketplaceIds: [{ required: true, message: '请选择适用站点' }],
  })
  const refsMap = {
    budgetRef: ref(),
    bidRef: ref(),
    switchRef: ref(),
    targetingRef: ref(),
  }
  const policyTypeRefMap = {
    BUDGET_POLICY: 'budgetRef',
    BIDDING_POLICY: 'bidRef',
    SWITCH_POLICY: 'switchRef',
    TARGETING_POLICY: 'targetingRef',
  }

  const showAddDialog = ref(props.isShow)
  const formInfo = ref<any>({})
  const formRef = ref()
  const submitLoading = ref(false)

  // 关闭
  function closedDialog() {
    showAddDialog.value = false
    emit('closed')
  }
  // 保存模板
  async function submitData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    let refName = policyTypeRefMap[formInfo.value.policyType]
    let refValid = refsMap[refName].value.validateData()
    if (!refValid) return false
    let _params = refsMap[refName].value.setCreateData()
    let res: any = await createPolicyTemplateList({
      ...formInfo.value,
      ..._params,
    })
    if (res) {
      Message.success('保存成功')
      emit('success')
      closedDialog()
      return true
    }
    return false
  }
</script>
<style lang="less" scoped>
  .title {
    padding-left: 20px;
    border-left: 2px solid rgb(var(--primary-6));
    margin-bottom: 20px;
  }
  .edit-con {
    max-height: calc(84vh - 140px);
    overflow-x: hidden;
    overflow-y: auto;
  }
</style>
